﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Threading;
using System.Windows.Shapes;
using System.Xml;
//-- winform namespace
using System.Windows.Forms;
using System.Drawing;
//-- microsoft namesapces
using Microsoft.MediaCenter.Samples.MediaState;
using Microsoft.Win32;

namespace omaura_oled
{
    /// <summary>
    /// Interaction logic for OmauraOled.xaml
    /// </summary>
    public partial class OmauraOled : Window
    {
        #region "Parameters"
        //--

        #region "Version & debug mode"
        //-- version
        public string Version = "1.2.0.2";

        //-- debug parameter
        public bool DebugModeEnable = false;
        //--
        #endregion "Version & debug mode"

        #region "USB Com"
        //-- serial port
        public System.IO.Ports.SerialPort serialPort1 = new System.IO.Ports.SerialPort();
        //--
        #endregion "USB Com"

        #region "WPF interface parameters"
        //-- general parameters
        public bool OledIsEnable;
        public bool LogoIsEnable;
        public bool BackgroundIsEnable;
        public bool ProgressBarIsEnable = true;

        //-- animations
        private DoubleAnimation FadeOut = new DoubleAnimation(0, new Duration(new TimeSpan(0, 0, 1)));
        private DoubleAnimation FadeIn = new DoubleAnimation(1, new Duration(new TimeSpan(0, 0, 1)));

        //-- zindex
        private int FrontPosition = 100;
        private int BackPosition = 0;
        //--
        #endregion "WPF interface parameters"

        #region "Notify icon"
        //-- notify icons/context menu parameters
        NotifyIcon omauraNotifyIcon;
        ContextMenuStrip contextMenuStripOmaura;
        ToolStripItem ContextMenuStripSettings;
        ToolStripItem ContextMenuStripExit;
        bool contextMenuShowed = false;
        //--
        #endregion "Notify icon"

        #region "Classes instances"
        //-- instances
        public ReadConfigFile RCF;
        public WriteConfigFile WCF;
        public ReadThemes RT;
        public Lang LanguageConfig;
        public ReadLanguages LanguageSearch;
        public ScriptReader ScriptRead;
        private IconsManager iconsManager;
        public DisplayClass displayClass;
        public WeatherReader weather;
        private UpdateSoftware UpdateSoft;
        public Microsoft.MediaCenter.Samples.MediaState.MediaState mediaState;

        public ApiInterface API_Oled;
        //--
        #endregion "Classes instances"

        #region "Fonts"
        //- Fonts definition
        public Font textFont1 = null;
        public Font textFont2 = null;
        public Font textFont3 = null;
        public Font textFontClock = null;
        //--
        #endregion "Fonts"

        #region "Paths"
        //-- install path
        public string InstallPath = "";

        //- Backgrounds and Icons folder
        public string iconsFolderPath;// = ".\\Resources\\Themes\\Omaura(Default)\\Img\\";
        //--
        #endregion "Path to images"

        #region "Timers & timers parameters"
        //-- timers
        //--- definitions
        public DispatcherTimer timerTimeCurrent = new DispatcherTimer();
        public DispatcherTimer timerVolumeDisplay = new DispatcherTimer();
        public DispatcherTimer timerWeatherDisplay = new DispatcherTimer();
        public DispatcherTimer timerScrollingText = new DispatcherTimer();
        public DispatcherTimer timerWeatherGet = new DispatcherTimer();
        //--- parameters
        private TimeSpan timerTimeCurrent_Interval = new TimeSpan(0,0,1);
        private TimeSpan timerScrollingText_Interval = new TimeSpan(0, 0, 0, 0, 100);
        private TimeSpan timerWeatherGet_Interval = new TimeSpan(0, 5, 0);

        //-- timers attribute
        public DispatcherTimer text_Timer_w = new DispatcherTimer();
        public DispatcherTimer text_Timer_b = new DispatcherTimer();
        public DispatcherTimer timerWeatherDisplaySearch = new DispatcherTimer();
        //--- parameters
        private TimeSpan text_Timer_w_Interval = new TimeSpan(0, 0, 3); // 3 seconds
        private TimeSpan text_Timer_b_Interval = new TimeSpan(0, 0, 3); // 3 seconds
        private TimeSpan timerVolumeDisplay_Interval = new TimeSpan(0, 0, 0, 0, 100); // 1seconds ( 10 x 100ms)
        private TimeSpan timerWeatherDisplay_Interval = new TimeSpan(0, 0, 5); // 5 seconds
        private TimeSpan timerWeatherDisplaySearch_Interval = new TimeSpan(0, 30, 0);// 30 minutes: see the weather.com rules

        //--
        public bool textByeDisplay = false;
        //--
        public int timerVolumeDisplay_Counter = 0;
        private bool hasShownVolume = false;
        //--
        #endregion "Timers & timers parameters"

        #region "Mediastate sessions parameters"
        //-- Session Parameters save temporary
        public bool TitleDVD_IsScrolling = false;
        public bool TitleVideo_IsScrolling = false;
        public bool TitleMusic_IsScrolling = false;
        public bool TitleCD_IsScrolling = false;
        public bool TitleTVRec_IsScrolling = false;
        public bool TitleTV_IsScrolling = false;
        public bool TitlePictures_IsScrolling = false;
        public bool TitleRadio_IsScrolling = false;

        //-- Session parameters
        public bool HomeDisplayed = false;
        //--
        #endregion "Mediastate sessions parameters"

        #region "Weather parameters"
        //--
        public string[][] WeatherCitySearchResult = new string[20][];
        //--
        #endregion "Weather parameters"

        #region "Internet connexion"
        //--
        public bool InternetConnexionUp = false;
        public string InternetConnexionUrl = "http://www.google.com";
        //--
        #endregion "Internet connexion"

        //--
        #endregion "Parameters"

        #region "Constructors"
        //--
        public OmauraOled()
        {
            #region "Init interface"
            //-- init interface components
            InitializeComponent();
            //--
            #endregion "Init interface"

            #region "Check&Validate AppData Folder"
            //--
            AppDataValidator.CheckAppDataFolders();
            AppDataValidator.CreateAppDataFolders();
            //--
            #endregion "Check&Validate AppData Folder"

            #region "Read Install Path"
            //-- read Install Path
            ReadInstallPath();
            //--
            #endregion "Read Install Path"

            #region "Set interface"
            //-- Debug interface
            if (!DebugModeEnable)
            {
                //-- interface "hide"
                labelBuild.Opacity = 0;
            }

            //-- init interface values
            //--- canvas app button
            this.canvasAppActions.Opacity = 0;
            //--- canvas content
            this.canvasStatus.Opacity = 1;
            this.canvasUpdate.Opacity = 0;
            this.canvasAbout.Opacity = 0;
            this.canvasTools.Opacity = 0;
            //--- canvas tools content
            this.CanvasTContentGeneral.Opacity = 1;
            this.CanvasTContentMessages.Opacity = 0;
            this.CanvasTContentThemes.Opacity = 0;
            this.CanvasTContentWeather.Opacity = 0;
            //--- canvas navigations
            this.canvasNavigation.Opacity = 1;
            this.canvasNavigationTools.Opacity = 0;
            //--- canvas close
            this.canvasAppActionsBg.Opacity = 0;
            //--- canvas disableclicks
            this.gridDisableContentClick.Opacity = 0;
            this.gridDisableNavigClick.Opacity = 0;

            //-- set up z-order
            //--- back
            Canvas.SetZIndex(canvasXBack, BackPosition);
            Canvas.SetZIndex(canvasAppActions, FrontPosition);
            //--- content
            Canvas.SetZIndex(canvasStatus, FrontPosition);
            Canvas.SetZIndex(canvasUpdate, BackPosition);
            Canvas.SetZIndex(canvasAbout, BackPosition);
            Canvas.SetZIndex(canvasTools, BackPosition);
            //--- navigation
            Canvas.SetZIndex(canvasNavigation, FrontPosition);
            Canvas.SetZIndex(canvasNavigationTools, BackPosition);
            //--- disable grid
            Canvas.SetZIndex(gridDisableContentClick, BackPosition);
            Canvas.SetZIndex(gridDisableNavigClick, BackPosition);
            
            //-- disbale button download
            buttonUBetaDownload.IsEnabled = false;
            buttonUStableDownload.IsEnabled = false;
            buttonUBetaDownload.Opacity = 0;
            buttonUStableDownload.Opacity = 0;

            //-- empty the label version
            labelUVersionBetaText.Content = "";
            labelUVersionStableText.Content = "";

            //--
            #endregion "Set interface"

            #region "Notify Icon"
            //-------
            // WARNING:
            //
            // WAITING FOR THE WPF CLASS for notify icon ... 
            // currently using the framework 2.0 / winform one ...
            //-------


            //-- init the notify icon
            //--- notify icon
            this.omauraNotifyIcon = new NotifyIcon();
            this.omauraNotifyIcon.Icon = new System.Drawing.Icon(".//omaura.ico");
            this.omauraNotifyIcon.Text = "omaura oled";
            this.omauraNotifyIcon.Visible = true;
            this.omauraNotifyIcon.ContextMenuStrip = this.contextMenuStripOmaura;
            this.omauraNotifyIcon.DoubleClick += new EventHandler(omauraNotifyIcon_DoubleClick);
            this.omauraNotifyIcon.MouseUp += new System.Windows.Forms.MouseEventHandler(omauraNotifyIcon_MouseUp);

            //-- init context menu and items
            this.ContextMenuStripExit = new ToolStripMenuItem();
            this.ContextMenuStripSettings = new ToolStripMenuItem();
            this.contextMenuStripOmaura = new ContextMenuStrip();

            //--- contextMenuStripOmaura
            this.contextMenuStripOmaura.Items.AddRange(new ToolStripItem[] {
                        this.ContextMenuStripSettings,
                        this.ContextMenuStripExit});
            this.contextMenuStripOmaura.Name = "contextMenuStripOmaura";
            this.contextMenuStripOmaura.Size = new System.Drawing.Size(127, 48);

            //--- ContextMenuStripSettings
            this.ContextMenuStripSettings.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Bold);
            this.ContextMenuStripSettings.Name = "ContextMenuStripSettings";
            this.ContextMenuStripSettings.Size = new System.Drawing.Size(126, 22);
            this.ContextMenuStripSettings.Text = "omaura oled";
            this.ContextMenuStripSettings.Click += new EventHandler(this.ContextMenuStripSettings_Click);

            //--- ContextMenuStripExit
            this.ContextMenuStripExit.Font = new System.Drawing.Font("Tahoma", 9F, System.Drawing.FontStyle.Regular);
            this.ContextMenuStripExit.Name = "ContextMenuStripExit";
            this.ContextMenuStripExit.Size = new System.Drawing.Size(126, 22);
            this.ContextMenuStripExit.Text = "Exit";
            this.ContextMenuStripExit.Click += new EventHandler(this.ContextMenuStripExit_Click);
            //--
            #endregion "Notify Icon"

            #region "Classes Initialization"
            //-- Init Classes
            LanguageSearch = new ReadLanguages(this);
            ScriptRead = new ScriptReader(this);
            RT = new ReadThemes(this);
            RCF = new ReadConfigFile(this);
            WCF = new WriteConfigFile(this);
            LanguageConfig = new Lang(RCF.Language, this);

            //-- Init Display Classes
            iconsManager = new IconsManager(this);
            displayClass = new DisplayClass(this, RCF);

            //-- Init http classes
            weather = new WeatherReader(this);
            UpdateSoft = new UpdateSoftware(this);

            //-- Init Mediastate library
            mediaState = new Microsoft.MediaCenter.Samples.MediaState.MediaState();

            //-- Init Pluggin
            API_Oled = new ApiInterface(this);

            //--
            #endregion "Classes Initialization"

            #region "Init display parameters"
            //-- Init parameters
            if (RCF.LogoIsEnable == 1)
                LogoIsEnable = true;
            else
                LogoIsEnable = false;
            //---
            if (RCF.OledBackGroundIsEnable == 1)
                BackgroundIsEnable = true;
            else
                BackgroundIsEnable = false;
            //---
            if (RCF.OledIsEnable == 1)
                OledIsEnable = true;
            else
                OledIsEnable = false;
            //--
            #endregion "Init display parameters"

            #region "Internet connexion test"
            //--
            InternetConnexionUp = HTTPTest.ConnectionAvailable(InternetConnexionUrl);
            //--
            #endregion "Internet connexion test"
        }
        private void OmauraOled_Loaded(object sender, RoutedEventArgs e)
        {
            #region "Set parameters"
            //-- set parameters
            bool deviceFound = false;
            controlIconsFolder(iconsFolderPath);
            //--
            #endregion "Set parameters"

            #region "Mediastate & events OR Plugin"
            //--
            CreateEventHandlersOmaura();
            CreateEventHandlerPower();

            //--
            if (RCF.PluginIsEnable == 1)
            {
                API_Oled.API_Start();
            }
            else
            {
                //-- Init mediastate connection
                mediaState.Connect();

                //-- Init the events
                CreateEventHandler();
                CreateEventHandlers();
            }
            //--
            #endregion "Mediastate & events OR Plugin"

            #region "Fonts initialization"
            //-- Init Fonts
            //--- check the size parameters functions
            textFont1 = new Font(RCF.get_FontType(), RCF.get_FontTypeSize() - 2);
            textFont2 = new Font(RCF.get_FontType(), RCF.get_FontTypeSize());
            textFont3 = new Font(RCF.get_FontType(), RCF.get_FontTypeSize() + 2);
            textFontClock = new Font(RCF.get_FontTypeClock(), RCF.get_FontTypeClockSize());
            //--
            #endregion "Fonts initialization"

            #region "Launch connection"
            //-- init the serial port
            serialPort1.ReadTimeout = 50;
            serialPort1.NewLine = "\n";

            //-- Launch Connection
            //comboBox2.Items.Add(System.IO.Ports.SerialPort.GetPortNames());
            foreach (string Port in System.IO.Ports.SerialPort.GetPortNames())
                comboBox2.Items.Add(Port);

            for (int i = 0; i < comboBox2.Items.Count; i++)
            {
                comboBox2.SelectedIndex = i;
                serialPort1.PortName = comboBox2.Text;
                serialPort1.BaudRate = 500000;//(int)numericUpDown1.Value;
                try
                {
                    serialPort1.Open();
                    if (serialPort1.IsOpen)
                    {
                        byte[] buffer = new byte[2];
                        buffer[0] = 0x70; // Start code
                        buffer[1] = 0x71; // Recognition code
                        serialPort1.Write(buffer, 0, 2);
                        string tempString = serialPort1.ReadLine();
                        if (tempString.Length > 1)
                        {
                            if (tempString.Substring(0, tempString.IndexOf(" ")) == "OLED")
                                deviceFound = true;
                        }
                    }
                }
                catch (Exception ex)
                {
                    //Log.Write(ex);
                }
                if (deviceFound)
                    i = comboBox2.Items.Count;
                else
                    serialPort1.Close();
            }
            if (deviceFound)
            {
                checkBox1.IsChecked = true;
                labelSUSBConnected.Content = "Device found";
            }
            else
            {
                comboBox2.SelectedIndex = 0;
                labelSUSBConnected.Content = "Device not found";
            }
            //--
            #endregion "Launch connection"

            #region "Windows visibility"
            //-- put the form in the tray
            this.ShowInTaskbar = false;
            this.Visibility = System.Windows.Visibility.Hidden;
            //--
            #endregion "Windows visibility"

            #region "Set up timers"
            //-- Set up timers
            text_Timer_w.Interval = text_Timer_w_Interval;
            text_Timer_b.Interval = text_Timer_b_Interval;
            timerVolumeDisplay.Interval = timerVolumeDisplay_Interval;
            timerTimeCurrent.Interval = timerTimeCurrent_Interval;
            timerScrollingText.Interval = timerScrollingText_Interval;
            timerWeatherDisplay.Interval = timerWeatherDisplay_Interval;
            timerWeatherDisplaySearch.Interval = timerWeatherDisplaySearch_Interval;
            timerWeatherGet.Interval = timerWeatherGet_Interval;

            timerWeatherDisplaySearch.Start();
            //--
            #endregion "Set up timers"

            #region "Start Classes"
            //--
            if(InternetConnexionUp)
                weather.UpdateWeatherData();
            //--
            #endregion "Start Classes"

            #region "Start the display"
            //-- Erase Screen
            displayClass.eraseScreen();

            if (LogoIsEnable)
            {
                //-- Display Fake Gif
                DisplayFakeGif("Welcome");
            }
            else
            {
                //-- Display Start Message
                displayClass.displayTitle(RCF.StartMessage);

                //-- Start StartMessage timer
                text_Timer_w.Start();
            }

            //--
            #endregion "Start the display"
        }
        private void OmauraOled_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            if (this.Visibility == System.Windows.Visibility.Hidden)
            {
                // configFile.closeFile();
                if (serialPort1.IsOpen)
                    // remove the time current display
                    timerTimeCurrent.Stop();

                // if text not display
                // cancel closing, do the stuff and after we continue to close ...
                if (!textByeDisplay)
                {
                    e.Cancel = true;

                    timerTimeCurrent.Stop();

                    displayClass.eraseScreen();

                    if (LogoIsEnable)
                    {
                        // display fake gif
                        DisplayFakeGif("Bye");
                        timerTimeCurrent.Stop();
                        text_Timer_b.Start();
                    }
                    else
                    {
                        // display message
                        displayClass.displayTitle(RCF.EndMessage);

                        // start timer text bye
                        text_Timer_b.Start();
                    }
                }
                else // if text display close
                {
                    e.Cancel = false;

                    //-- send death image
                    if (RCF.SendDeathImage == 1)
                    {
                        displayClass.displayDeathImage();
                    }

                    //-- release resources
                    serialPort1.Close();
                    mediaState.Dispose();


                    //-- stop api
                    API_Oled.API_Stop();
                }
            }
            else
            {
                e.Cancel = true;
                this.WindowState = WindowState.Minimized;
                this.ShowInTaskbar = false;
            }
        }
        private void OmauraOled_Closed(object sender, EventArgs e)
        {
            //-- stop timer updates
            timerWeatherDisplaySearch.Stop();
            
            //-- remove the notification icon
            this.omauraNotifyIcon.Dispose();

            //-- release Port com-USB, the mediastate dll, erase screen
            displayClass.eraseScreen();
            serialPort1.Close();
            mediaState.Dispose();
        }
        //--
        #endregion "Constructors"

        #region "Methods"
        //--

        #region "PowerModeChanged"
        //-- hibernate, sleeping mode event creation
        protected void CreateEventHandlerPower()
        {
            Microsoft.Win32.SystemEvents.PowerModeChanged += new PowerModeChangedEventHandler(PowerMode_Changed);
        }

        //-- power mode change methods
        public void PowerMode_Changed(object sender, PowerModeChangedEventArgs e)
        {
            //Log.Write("power mode changed to " + e.Mode.ToString());

            // Case hibernate / sleep
            if (e.Mode == PowerModes.Suspend)
            {
                timerTimeCurrent.Stop();

                if (RCF.SendDeathImage == 1)
                {
                    displayClass.displayDeathImage();
                }
                else
                {
                    displayClass.eraseScreen();
                }
                serialPort1.Close();
            }
            // Case go back to life :)
            if (e.Mode == PowerModes.Resume)
            {
                serialPort1.Open();
                timerTimeCurrent.Start();
            }
        }
        //--
        #endregion "PowerModeChanged"

        #region "Gif Effect Method"
        //-- Methods display moving image welcome
        public void DisplayFakeGif(string parametersString)
        {
            //-- parameters
            int iImage;
            int numberOfPicturesWelcome, numberOfPicturesBye;

            //-- read number of images
            if (parametersString == "Welcome")
            {
                string[] namesWelcome = Directory.GetFiles(".\\Resources\\Logo\\Welcome\\", "*.bmp");
                numberOfPicturesWelcome = namesWelcome.Length;

                for (iImage = 0; iImage < numberOfPicturesWelcome; iImage++)
                    displayClass.displayLogo(".\\Resources\\Logo\\Welcome\\omaura-welcome_" + iImage + ".bmp");
            }
            if (parametersString == "Bye")
            {
                string[] namesBye = Directory.GetFiles(".\\Resources\\Logo\\Bye\\", "*.bmp");
                numberOfPicturesBye = namesBye.Length;

                for (iImage = 0; iImage < numberOfPicturesBye; iImage++)
                    displayClass.displayLogo(".\\Resources\\Logo\\Bye\\omaura-bye_" + iImage + ".bmp");
            }

            displayClass.eraseScreen();
            timerTimeCurrent.Start();
        }
        //--
        #endregion "Gif Effect Method"

        #region "Omaura timers"
        //-- timers
        //--- weather
        void timerWeatherDisplaySearch_Tick(object sender, EventArgs e)
        {
            InternetConnexionUp = HTTPTest.ConnectionAvailable(InternetConnexionUrl);
            
            if(InternetConnexionUp)
                weather.UpdateWeatherData();
        }
        void timerWeatherDisplay_Tick(object sender, EventArgs e)
        {
            timerWeatherDisplay.IsEnabled = false;//.Stop();
            displayClass.eraseScreen();

            if (RCF.PluginIsEnable == 1)
                displayClass.restoreDisplay_API();
            else
                displayClass.restoreDisplay();
        }

        //--- time current
        void timerTimeCurrent_Tick(object sender, EventArgs e)
        {
            displayClass.displayCurrentTime();
        }

        //--- volume display
        void timerVolumeDisplay_Tick(object sender, EventArgs e)
        {
            if (timerVolumeDisplay_Counter == 10)
            {
                timerVolumeDisplay.IsEnabled = false;
                timerVolumeDisplay_Counter = 0;

                if (RCF.PluginIsEnable == 1)
                    displayClass.restoreDisplay_API();
                else
                    displayClass.restoreDisplay();
            }
            else
                timerVolumeDisplay_Counter++;
        }

        //--- welcome and bye message
        void TimerTextHello(Object myObject, EventArgs myEventArgs)
        {
            text_Timer_w.Stop();
            // After Welcome Text Display, display timecurrent 
            displayClass.eraseScreen();

            if (RCF.PluginIsEnable == 1)
                API_Oled.API_Start();
            else
                timerTimeCurrent.Start();
        }
        void TimerTextBye(Object myObject, EventArgs myEventArgs)
        {
            //-- stop timer / erase screen / set the boolean text display to true 
            //              / close again(with the parameter textByeDisplay to true it should directly close the app)
            text_Timer_b.Stop();
            displayClass.eraseScreen();
            textByeDisplay = true;
            this.Close();
        }
        //--
        #endregion "Omaura timers"

        #region "Events"
        //-- Events Definition
        protected void CreateEventHandlersOmaura()
        {
            // Omaura text timer events
            text_Timer_b.Tick += new EventHandler(TimerTextBye);
            text_Timer_w.Tick += new EventHandler(TimerTextHello);
            timerVolumeDisplay.Tick += new EventHandler(timerVolumeDisplay_Tick);
            timerTimeCurrent.Tick += new EventHandler(timerTimeCurrent_Tick);
            timerScrollingText.Tick += new EventHandler(timerScrollingText_Tick);
            timerWeatherDisplay.Tick += new EventHandler(timerWeatherDisplay_Tick);
            timerWeatherDisplaySearch.Tick += new EventHandler(timerWeatherDisplaySearch_Tick);
        }
        protected void CreateEventHandler()
        {
            // Events Detection
            mediaState.OnMSASEvent += new Microsoft.MediaCenter.Samples.MediaState.MediaState.MSASEventHandler(ms_OnMSASEvent);
        }
        protected void CreateEventHandlers()
        {
            // Music event handlers
            mediaState.Music.MediaChanged += new EventHandler(Music_MediaChanged);
            mediaState.Music.TrackTimeChanged += new EventHandler(Music_TrackTimeChanged);

            // CD event handlers
            mediaState.CD.MediaChanged += new EventHandler(CD_MediaChanged);
            mediaState.CD.TrackTimeChanged += new EventHandler(CD_TrackTimeChanged);

            // DVD event handlers
            mediaState.DVD.TrackTimeChanged += new EventHandler(DVD_TrackTimeChanged);
            mediaState.DVD.MediaChanged += new EventHandler(DVD_MediaChanged);

            // Pictures event handlers
            mediaState.Pictures.CurrentPictureChanged += new EventHandler(Pictures_CurrentPictureChanged);

            // Radio event handlers
            mediaState.Radio.FrequencyChanged += new EventHandler(Radio_FrenquencyChanged);

            // Video event handlers
            mediaState.Video.MediaChanged += new EventHandler(Video_MediaChanged);
            mediaState.Video.TrackTimeChanged += new EventHandler(Video_TrackTimeChanged);

            // TV event handlers
            mediaState.TV.MediaChanged += new EventHandler(TV_MediaChanged);
            //mediaState.TV.TrackTimeChanged += new EventHandler(TV_TrackTimeChanged);

            // Recorded Shows event handlers
            mediaState.TVRecorded.MediaChanged += new EventHandler(TVRecorded_MediaChanged);
            mediaState.TVRecorded.TrackTimeChanged += new EventHandler(TVRecorded_TrackTimeChanged);

            // General Events
            mediaState.MediaCenter.NavigationChanged += new EventHandler(MediaCenter_NavigationChanged);
            mediaState.MediaCenter.VolumeChanged += new EventHandler(MediaCenter_VolumeChanged);
            mediaState.MediaCenter.MuteChanged += new EventHandler(MediaCenter_MuteChanged);
            mediaState.MediaCenter.Ended += new EventHandler(MediaCenter_Ended);
        }

        //-- Event handler on MediaControl Status / Value
        private void ms_OnMSASEvent(object state, MediaStatusEventArgs args)
        {
            // Position in mediacenter
            MediaStatusPropertyTag navigationPropertyTag = mediaState.MediaCenter.Navigation;

            // Prevent strange display when the software start and Medicenter already launched
            text_Timer_w.Stop();

            // if no volume display
            if (!timerVolumeDisplay.IsEnabled && !timerWeatherDisplay.IsEnabled && HomeDisplayed)
            {
                if (mediaState.Music.Play
                    || mediaState.CD.Play
                    || mediaState.TV.Play
                    || mediaState.TVRecorded.Play
                    || mediaState.Radio.Play
                    || mediaState.DVD.Play
                    || mediaState.Video.Play
                    || mediaState.Pictures.Play
                    )
                    displayClass.displayIconPlay();
                else if (mediaState.Music.Pause
                    || mediaState.CD.Pause
                    || mediaState.TV.Pause
                    || mediaState.TVRecorded.Pause
                    || mediaState.Radio.Pause
                    || mediaState.DVD.Pause
                    || mediaState.Video.Pause
                    || mediaState.Pictures.Pause
                    )
                    displayClass.displayIconPause();
                if (mediaState.Music.Stop
                    && mediaState.CD.Stop
                    && mediaState.TV.Stop
                    && mediaState.TVRecorded.Stop
                    && mediaState.Radio.Stop
                    && mediaState.DVD.Stop
                    && mediaState.Video.Stop
                    //-- added for no icon display when mediacenter shut down
                    && mediaState.MediaCenter.Active
                    )
                    displayClass.displayIconStop();
                else if (!mediaState.Music.FastForward.ToString().Equals("Off")
                    || !mediaState.CD.FastForward.ToString().Equals("Off")
                    || !mediaState.TV.FastForward.ToString().Equals("Off")
                    || !mediaState.TVRecorded.FastForward.ToString().Equals("Off")
                    || !mediaState.Radio.FastForward.ToString().Equals("Off")
                    || !mediaState.DVD.FastForward.ToString().Equals("Off")
                    || !mediaState.Video.FastForward.ToString().Equals("Off")
                    || !mediaState.Pictures.FastForward.ToString().Equals("Off")
                    )
                    displayClass.displayIconFF();
                else if (!mediaState.Music.Rewind.ToString().Equals("Off")
                    || !mediaState.CD.Rewind.ToString().Equals("Off")
                    || !mediaState.TV.Rewind.ToString().Equals("Off")
                    || !mediaState.TVRecorded.Rewind.ToString().Equals("Off")
                    || !mediaState.Radio.Rewind.ToString().Equals("Off")
                    || !mediaState.DVD.Rewind.ToString().Equals("Off")
                    || !mediaState.Video.Rewind.ToString().Equals("Off")
                    || !mediaState.Pictures.Rewind.ToString().Equals("Off")
                    )
                    displayClass.displayIconRW();
            }
        }

        //-- Events TV Recorded
        void TVRecorded_TrackTimeChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- if text already in an another session scrolling stop
            if (TitleMusic_IsScrolling
                || TitleCD_IsScrolling
                || TitleDVD_IsScrolling
                || TitleRadio_IsScrolling
                || TitleTV_IsScrolling
                || TitleVideo_IsScrolling
                || TitlePictures_IsScrolling
                )
                ReinitializationScrolling();

            //-- display time
            if (ScriptRead.TVRecordedTimeTotal)
                displayClass.displayTimeAndTotal(TVRecTimeDisplayAnalyse(ScriptRead.TVRecordedTime), mediaState.TVRecorded.MediaTime);
            else
                displayClass.displayTime(TVRecTimeDisplayAnalyse(ScriptRead.TVRecordedTime));

            //-- display title
            if (!timerScrollingText.IsEnabled)
                displayClass.displayTitle(TVRecDisplayAnalyse(ScriptRead.TVRecorded));
            else
                TitleTVRec_IsScrolling = true;
        }
        void TVRecorded_MediaChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- write nothing
            displayClass.displayTitle("");
        }

        //-- Events Video
        void Video_TrackTimeChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- if text already in an another session scrolling stop
            if (TitleMusic_IsScrolling
                || TitleCD_IsScrolling
                || TitleDVD_IsScrolling
                || TitleRadio_IsScrolling
                || TitleTV_IsScrolling
                || TitleTVRec_IsScrolling
                || TitlePictures_IsScrolling
                )
                ReinitializationScrolling();

            //--- time
            if (ScriptRead.VideoTimeTotal)
                displayClass.displayTimeAndTotal(VideoTimeDisplayAnalyse(ScriptRead.VideoTime), mediaState.Video.MediaTime);
            else
                displayClass.displayTime(VideoTimeDisplayAnalyse(ScriptRead.VideoTime));

            //-- title
            if (!timerScrollingText.IsEnabled)
                displayClass.displayTitle(VideoDisplayAnalyse(ScriptRead.Video));
            else
                TitleVideo_IsScrolling = true;
        }
        void Video_MediaChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- write nothing
            displayClass.displayTitle("");
        }

        //-- Events DVD
        void DVD_TrackTimeChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- if text already in an another session scrolling stop
            if (TitleMusic_IsScrolling
                || TitleVideo_IsScrolling
                || TitleCD_IsScrolling
                || TitleRadio_IsScrolling
                || TitleTV_IsScrolling
                || TitleTVRec_IsScrolling
                || TitlePictures_IsScrolling
                )
                ReinitializationScrolling();

            //-- display Time
            if (ScriptRead.DVDTimeTotal)
                displayClass.displayTimeAndTotal(DVDTimeDisplayAnalyse(ScriptRead.DVDTime), mediaState.DVD.MediaTime);
            else
                displayClass.displayTime(DVDTimeDisplayAnalyse(ScriptRead.DVDTime));


            //-- display title
            if (!timerScrollingText.IsEnabled && !mediaState.Pictures.Play)
                displayClass.displayTitle(DVDDisplayAnalyse(ScriptRead.DVD));
            else
                TitleDVD_IsScrolling = true;
        }
        void DVD_MediaChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- write nothing
            displayClass.displayTitle("");
        }

        //-- Events CD
        void CD_TrackTimeChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- if text already in an another session scrolling stop
            if (TitleMusic_IsScrolling
                || TitleVideo_IsScrolling
                || TitleDVD_IsScrolling
                || TitleRadio_IsScrolling
                || TitleTV_IsScrolling
                || TitleTVRec_IsScrolling
                || TitlePictures_IsScrolling
                )
                ReinitializationScrolling();

            //-- display time
            if (ScriptRead.AudioCDTimeTotal)
                displayClass.displayTimeAndTotal(CDTimeDisplayAnalyse(ScriptRead.AudioCDTime), mediaState.CD.TrackDuration);
            else
                displayClass.displayTime(CDTimeDisplayAnalyse(ScriptRead.AudioCDTime));

            //-- display title
            if (!timerScrollingText.IsEnabled && !mediaState.Pictures.Play)
                displayClass.displayTitle(CDDisplayAnalyse(ScriptRead.AudioCD));
            else
                TitleCD_IsScrolling = true;
        }
        void CD_MediaChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- write nothing
            displayClass.displayTitle("");
        }

        //-- Events Music
        void Music_TrackTimeChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- if text already in an another session scrolling stop
            if (TitleVideo_IsScrolling
                || TitleCD_IsScrolling
                || TitleDVD_IsScrolling
                || TitleRadio_IsScrolling
                || TitleTV_IsScrolling
                || TitleTVRec_IsScrolling
                )
                ReinitializationScrolling();

            //--- time
            if (ScriptRead.AudioMusicTimeTotal)
                displayClass.displayTimeAndTotal(MusicTimeDisplayAnalyse(ScriptRead.AudioMusicTime), mediaState.Music.TrackDuration);
            else
                displayClass.displayTime(MusicTimeDisplayAnalyse(ScriptRead.AudioMusicTime));

            //-- title
            if (!timerScrollingText.IsEnabled && !mediaState.Pictures.Play)
                displayClass.displayTitle(MusicDisplayAnalyse(ScriptRead.AudioMusic));
            else
                TitleMusic_IsScrolling = true;
        }
        void Music_MediaChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- write nothing
            displayClass.displayTitle("");
        }

        //-- Events Radio
        void Radio_FrenquencyChanged(object sender, EventArgs e)
        {
            displayClass.displayTimeEmpty();

            displayClass.displayTitle(RadioDisplayAnalyse(ScriptRead.Radio));
        }

        //-- Events TV
        void TV_MediaChanged(object sender, EventArgs e)
        {
            //displayClass.displayTitle(mediaState.TV.Channel + mediaState.TV.MediaName);
            displayClass.displayTitle(TVDisplayAnalyse(ScriptRead.TV));
        }

        //-- Events Pictures
        void Pictures_CurrentPictureChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //displayClass.displayTitle(mediaState.Pictures.CurrentPicture);
            displayClass.displayTitle(PicturesDisplayAnalyse(ScriptRead.Pictures));
        }

        //-- Events Mediacenter General
        void MediaCenter_NavigationChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            MediaStatusPropertyTag navigationPropertyTag = mediaState.MediaCenter.Navigation;
            switch (navigationPropertyTag)
            {
                case MediaStatusPropertyTag.FS_TV:
                    HomeDisplayed = true;
                    displayClass.displayBkgndTVTuner();
                    break;

                case MediaStatusPropertyTag.FS_DVD:
                    HomeDisplayed = true;
                    displayClass.displayBkgndDVD();
                    break;

                case MediaStatusPropertyTag.FS_Guide:
                    HomeDisplayed = true;
                    displayClass.displayBkgndHome();
                    break;

                case MediaStatusPropertyTag.FS_Music:
                    HomeDisplayed = true;
                    displayClass.displayBkgndAudio();
                    break;

                case MediaStatusPropertyTag.FS_Photos:
                    HomeDisplayed = true;
                    displayClass.displayBkgndPhotos();
                    break;

                case MediaStatusPropertyTag.FS_Videos:
                    HomeDisplayed = true;
                    displayClass.displayBkgndVideo();
                    break;

                case MediaStatusPropertyTag.FS_RecordedShows:
                    HomeDisplayed = true;
                    displayClass.displayBkgndPVR();
                    break;

                case MediaStatusPropertyTag.FS_Home:
                    if (!HomeDisplayed)
                    {
                        displayClass.displayBkgndHome();
                    }
                    else
                    {
                        displayClass.displayBkgndHome2();
                    }
                    break;

                case MediaStatusPropertyTag.FS_Radio:
                    HomeDisplayed = true;
                    displayClass.displayBkgndRadio();
                    break;

                case MediaStatusPropertyTag.FS_Unknown:
                    HomeDisplayed = true;
                    displayClass.displayBkgndHome2();
                    break;

                default:
                    break;
            }
        }
        void MediaCenter_MuteChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- display mute/volume
            if (mediaState.MediaCenter.Mute)
                displayClass.displayVolume(0);
            else
                displayClass.displayVolume(mediaState.MediaCenter.Volume);
        }
        void MediaCenter_VolumeChanged(object sender, EventArgs e)
        {
            //-- stop event
            timerTimeCurrent.Stop();

            //-- display volume
            if (hasShownVolume)
                displayClass.displayVolume(mediaState.MediaCenter.Volume);
            else
                hasShownVolume = true;
        }
        void MediaCenter_Ended(object sender, EventArgs e)
        {
            timerScrollingText.IsEnabled = false;

            displayClass.eraseScreen();
            timerTimeCurrent.Start();
        }

        //-- Reinit the scrolling text for events display
        void ReinitializationScrolling()
        {
            //-- reset sessions parameters
            TitleDVD_IsScrolling = false;
            TitleVideo_IsScrolling = false;
            TitleMusic_IsScrolling = false;
            TitleCD_IsScrolling = false;
            TitleTVRec_IsScrolling = false;
            TitleTV_IsScrolling = false;
            TitlePictures_IsScrolling = false;
            TitleRadio_IsScrolling = false;

            //-- display nothing
            displayClass.displayTitle("");
        }

        //--
        #endregion "Events"

        #region "ScriptAnalyse"
        //-- Call
        public string CallDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "Name")
                    Result += mediaState.PhoneCall.Name;
                else if (StringParts[i] == "Number")
                    Result += mediaState.PhoneCall.Number;
                else
                    Result += StringParts[i];
            }
            return Result;
        }

        //-- DVD
        public string DVDDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";

            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "Chapter")
                    Result += mediaState.DVD.Chapter;
                else if (StringParts[i] == "MediaName")
                {
                    if (mediaState.DVD.MediaName.Equals(""))
                        Result += "unknown dvd";
                    else
                        Result += mediaState.DVD.MediaName;
                }
                else if (StringParts[i] == "TitleNumber")
                    Result += mediaState.DVD.TitleNumber;
                else if (StringParts[i] == "TotalTracks")
                    Result += mediaState.DVD.TotalTracks;
                else if (StringParts[i] == "TrackName")
                    Result += mediaState.DVD.TrackName;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        public int DVDTimeDisplayAnalyse(string StringToAnalyse)
        {
            int Result = 0;
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "MediaTime")
                    Result = (int)mediaState.DVD.MediaTime;
                if (StringParts[i] == "TrackTime")
                    Result = (int)mediaState.DVD.TrackTime;
                if (StringParts[i] == "TrackTime-MediaTime")
                    Result = (int)mediaState.DVD.TrackTime - (int)mediaState.DVD.MediaTime;
            }
            return Result;
        }

        //-- Video
        public string VideoDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "MediaName")
                    Result += mediaState.Video.MediaName;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        public int VideoTimeDisplayAnalyse(string StringToAnalyse)
        {
            int Result = 0;
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "MediaTime")
                    Result = (int)mediaState.Video.MediaTime;
                if (StringParts[i] == "TrackTime")
                    Result = (int)mediaState.Video.TrackTime;
                if (StringParts[i] == "TrackTime-MediaTime")
                    Result = (int)mediaState.Video.TrackTime - (int)mediaState.Video.MediaTime;
            }
            return Result;
        }

        //-- CD
        public string CDDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "ArtisteName")
                    Result += mediaState.CD.ArtistName;
                else if (StringParts[i] == "TrackName")
                    Result += mediaState.CD.TrackName;
                else if (StringParts[i] == "TrackNumber")
                    Result += mediaState.CD.TrackNumber;
                else if (StringParts[i] == "TotalTracks")
                    Result += mediaState.CD.TotalTracks;
                else if (StringParts[i] == "MediaName")
                    Result += mediaState.CD.MediaName;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        public int CDTimeDisplayAnalyse(string StringToAnalyse)
        {
            int Result = 0;
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "TrackDuration")
                    Result = (int)mediaState.CD.TrackDuration;
                if (StringParts[i] == "TrackTime")
                    Result = (int)mediaState.CD.TrackTime;
                if (StringParts[i] == "TrackTime-TrackDuration")
                    Result = (int)mediaState.CD.TrackTime - (int)mediaState.CD.TrackDuration;
            }
            return Result;
        }

        //-- Music
        public string MusicDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "ArtisteName")
                    Result += mediaState.Music.ArtistName;
                else if (StringParts[i] == "TrackName")
                    Result += mediaState.Music.TrackName;
                else if (StringParts[i] == "TrackNumber")
                    Result += mediaState.Music.TrackNumber;
                else if (StringParts[i] == "TotalTracks")
                    Result += mediaState.Music.TotalTracks;
                else if (StringParts[i] == "MediaName")
                    Result += mediaState.Music.MediaName;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        public int MusicTimeDisplayAnalyse(string StringToAnalyse)
        {
            int Result = 0;
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "TrackDuration")
                    Result = (int)mediaState.Music.TrackDuration;
                if (StringParts[i] == "TrackTime")
                    Result = (int)mediaState.Music.TrackTime;
                if (StringParts[i] == "TrackTime-TrackDuration")
                    Result = (int)mediaState.Music.TrackTime - (int)mediaState.Music.TrackDuration;
            }
            return Result;
        }

        //-- TV
        public string TVDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "Channel")
                    Result += mediaState.TV.Channel;
                else if (StringParts[i] == "MediaName")
                    Result += mediaState.TV.MediaName;
                else if (StringParts[i] == "ParentalAdvisoryRating")
                    Result += mediaState.TV.ParentalAdvisoryRating;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        public int TVTimeDisplayAnalyse(string StringToAnalyse)
        {
            int Result = 0;
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "MediaTime")
                    Result = (int)mediaState.TV.MediaTime;
                if (StringParts[i] == "TrackTime")
                    Result = (int)mediaState.TV.TrackTime;
                if (StringParts[i] == "TrackTime-MediaTime")
                    Result = (int)mediaState.TV.TrackTime - (int)mediaState.TV.MediaTime;
            }
            return Result;
        }

        //-- TV recorded
        public string TVRecDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "Channel")
                    Result += mediaState.TVRecorded.Channel;
                else if (StringParts[i] == "MediaName")
                    Result += mediaState.TVRecorded.MediaName;
                else if (StringParts[i] == "ParentalAdvisoryRating")
                    Result += mediaState.TVRecorded.ParentalAdvisoryRating;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        public int TVRecTimeDisplayAnalyse(string StringToAnalyse)
        {
            int Result = 0;
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "MediaTime")
                    Result = (int)mediaState.TVRecorded.MediaTime;
                if (StringParts[i] == "TrackTime")
                    Result = (int)mediaState.TVRecorded.TrackTime;
                if (StringParts[i] == "TrackTime-MediaTime")
                    Result = (int)mediaState.TVRecorded.TrackTime - (int)mediaState.TVRecorded.MediaTime;
            }
            return Result;
        }

        //-- Pictures
        public string PicturesDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "CurrentPicture")
                    Result += mediaState.Pictures.CurrentPicture;
                else
                    Result += StringParts[i];
            }
            return Result;
        }

        //-- Radio
        public string RadioDisplayAnalyse(string StringToAnalyse)
        {
            string Result = "";
            string[] StringParts = StringToAnalyse.Split('$');
            for (int i = 0; i < StringParts.Length; i++)
            {
                if (StringParts[i] == "Frequency")
                    Result += mediaState.Radio.Frequency;
                else
                    Result += StringParts[i];
            }
            return Result;
        }
        //--
        #endregion "ScriptAnalyse"

        #region "Get"
        //--
        public System.IO.Ports.SerialPort getSerialPort()
        {
            return serialPort1;
        }
        public IconsManager getIconManager()
        {
            return iconsManager;
        }
        public Font getTextFont(int font)
        {
            Font myFont = null;
            if (font == 1)
                myFont = textFont1;
            else if (font == 2)
                myFont = textFont2;
            else if (font == 3)
                myFont = textFont3;
            else if (font == 4)
                myFont = textFontClock;
            return myFont;
        }
        public string getIconsFolder()
        {
            return iconsFolderPath;
        }
        //--
        #endregion "Get"

        #region "Interface"
        //-- Etienne functions
        private void checkBox1_Click(object sender, RoutedEventArgs e)
        {
            if (checkBox1.IsChecked == true)
            {
                if (!serialPort1.IsOpen)
                {
                    try
                    {
                        serialPort1.PortName = comboBox2.SelectedValue.ToString();
                        serialPort1.Open();
                    }
                    catch (Exception ex)
                    {
                        Log.Write("exception: " + ex);
                        labelSUSBConnected.Content = "Device not found";
                        checkBox1.IsChecked = false;
                    }
                }
                if (serialPort1.IsOpen)
                {
                    labelSUSBConnected.Content = "Device found";
                    checkBox1.IsChecked = true;
                }
            }
            else
            {
                serialPort1.Close();
                labelSUSBConnected.Content = "Device not found";
                checkBox1.IsChecked = false;
            }
        }
        private void comboBox2_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (!serialPort1.IsOpen)
                serialPort1.PortName = comboBox2.SelectedValue.ToString();
        }
        //
        private void timerScrollingText_Tick(object sender, EventArgs e)
        {
            iconsManager.updateScrollingText();
        }
        public void controlIconsFolder(string path)
        {
            int errorNb = 0;
            System.Drawing.Bitmap temp;

            if (File.Exists(path + "Bkgnd_DVD.bmp") 
                && File.Exists(path + "Bkgnd_CD.bmp") 
                && File.Exists(path + "Bkgnd_PVR.bmp") 
                && File.Exists(path + "Bkgnd_Audio.bmp") 
                && File.Exists(path + "Bkgnd_Video.bmp") 
                && File.Exists(path + "Bkgnd_TVTuner.bmp") 
                && File.Exists(path + "Bkgnd_Home.bmp")
                && File.Exists(path + "Bkgnd_Home2.bmp")  
                && File.Exists(path + "Bkgnd_Photos.bmp")
                && File.Exists(path + "Bkgnd_Radio.bmp")
                && File.Exists(path + "D-Image.bmp")
                && File.Exists(path + "Sound.bmp")  
                && File.Exists(path + "Play.bmp") 
                && File.Exists(path + "Pause.bmp") 
                && File.Exists(path + "Stop.bmp") 
                && File.Exists(path + "Record.bmp") 
                && File.Exists(path + "RW.bmp") 
                && File.Exists(path + "FF.bmp"))
            {
                temp = new System.Drawing.Bitmap(path + "Bkgnd_DVD.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_CD.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_PVR.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_Audio.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_Video.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_TVTuner.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_Home.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_Home2.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_Photos.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "Bkgnd_Radio.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;
                temp = new System.Drawing.Bitmap(path + "D-Image.bmp");
                if (temp.Height != 64 || temp.Width != 256)
                    errorNb++;

                if (errorNb != 0)
                    Log.Write("Error: " + errorNb + " background file(s) does not have the required size.");
                else
                {
                    iconsFolderPath = path;
                    iconsManager.loadIconsFolder();
                }
            }
            else
                Log.Write("The folder specified does not contain the required files.");
        }

        // Apply parameters
        //-- stop displaying
        //-- reload all parameters
        private void Apply()
        {
            //-- stop
            timerScrollingText.Stop();
            timerTimeCurrent.Stop();
            displayClass.eraseScreen();
            //--- clear parameters
            iconsFolderPath = "";

            //-- reload
            //--- reload parameters
            RCF.ReadInfile();

            //--- reload script
            ScriptRead.ReadScriptFile();

            //--- reload fonts
            textFont1 = new Font(RCF.get_FontType(), RCF.get_FontTypeSize() - 2);
            textFont2 = new Font(RCF.get_FontType(), RCF.get_FontTypeSize());
            textFont3 = new Font(RCF.get_FontType(), RCF.get_FontTypeSize() + 2);
            textFontClock = new Font(RCF.get_FontTypeClock(), RCF.get_FontTypeClockSize());

            //--- reload images
            controlIconsFolder(iconsFolderPath);
            iconsManager.loadIconsFolder();

            //--- reload background
            if (mediaState.MediaCenter.Active)
            {
                MediaStatusPropertyTag navigationPropertyTag = mediaState.MediaCenter.Navigation;
                switch (navigationPropertyTag)
                {
                    case MediaStatusPropertyTag.FS_TV:
                        HomeDisplayed = true;
                        displayClass.displayBkgndTVTuner();
                        break;

                    case MediaStatusPropertyTag.FS_DVD:
                        HomeDisplayed = true;
                        displayClass.displayBkgndDVD();
                        break;

                    case MediaStatusPropertyTag.FS_Guide:
                        HomeDisplayed = true;
                        displayClass.displayBkgndHome();
                        break;

                    case MediaStatusPropertyTag.FS_Music:
                        HomeDisplayed = true;
                        displayClass.displayBkgndAudio();
                        break;

                    case MediaStatusPropertyTag.FS_Photos:
                        HomeDisplayed = true;
                        displayClass.displayBkgndPhotos();
                        break;

                    case MediaStatusPropertyTag.FS_Videos:
                        HomeDisplayed = true;
                        displayClass.displayBkgndVideo();
                        break;

                    case MediaStatusPropertyTag.FS_RecordedShows:
                        HomeDisplayed = true;
                        displayClass.displayBkgndPVR();
                        break;

                    case MediaStatusPropertyTag.FS_Home:
                        if (!HomeDisplayed)
                        {
                            displayClass.displayBkgndHome();
                        }
                        else
                        {
                            displayClass.displayBkgndHome2();
                        }
                        break;

                    case MediaStatusPropertyTag.FS_Radio:
                        HomeDisplayed = true;
                        displayClass.displayBkgndRadio();
                        break;

                    case MediaStatusPropertyTag.FS_Unknown:
                        HomeDisplayed = true;
                        displayClass.displayBkgndHome2();
                        break;

                    default:
                        break;
                }

            }
            else
            {
                //-- restart
                timerTimeCurrent.Start();
            }
        }

        //-- read InstallPath
        private void ReadInstallPath()
        {
            using (StreamReader fileReader = new StreamReader(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + "\\omaura\\omaura oled\\Install.txt"))
            {
                InstallPath = fileReader.ReadLine();
            }
        }

        //-- notify icon click events
        private void omauraNotifyIcon_MouseUp(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //---------
            // Warning:
            //
            // the mousePosition should be given by the event e.x e.y parameters
            // Right now the position is evaluated by the screen size :S
            //---------


            //-- if right click show the context menu
            if (e.Button == System.Windows.Forms.MouseButtons.Right)
            {
                //-- test is displayed
                //--- if none display -> show()
                if (!contextMenuShowed)
                {
                    //-- update parameter
                    contextMenuShowed = true;

                    //-- update interface
                    //--- context menu strip placement
                    System.Drawing.Point mousePosition;


                    /*
                    if (e.X != 0 && e.Y != 0)
                    {
                        mousePosition = new System.Drawing.Point(e.X, e.Y);
                    }
                    else
                    {
                        mousePosition = new System.Drawing.Point(1024, 768);
                    }

                    this.omauraNotifyIcon.BalloonTipText = e.X.ToString() + " - " + e.Y.ToString();
                    this.omauraNotifyIcon.ShowBalloonTip(2000);
                     */


                    int sX = Screen.PrimaryScreen.WorkingArea.Width;
                    int sY = Screen.PrimaryScreen.WorkingArea.Height;

                    mousePosition = new System.Drawing.Point(sX - contextMenuStripOmaura.Width, sY - contextMenuStripOmaura.Height);

                    //--- display the context menu strip
                    this.contextMenuStripOmaura.Show(mousePosition);
                }
                //--- else close()
                else
                {
                    //-- update parameter
                    contextMenuShowed = false;

                    //-- update interface
                    this.contextMenuStripOmaura.Close();
                }
            }
        }
        private void omauraNotifyIcon_DoubleClick(object sender, EventArgs e)
        {
            //-- if window hide, show it
            if (this.WindowState.Equals(WindowState.Minimized))
            {
                this.WindowState = WindowState.Normal;
                this.Visibility = Visibility.Visible;
                this.Topmost = true;
                this.ShowInTaskbar = true;
            }
            //-- else hide it
            else
            {
                this.WindowState = WindowState.Minimized;
                this.Visibility = Visibility.Hidden;
                this.Topmost = false;
                this.ShowInTaskbar = false;
            }
        }
        private void ContextMenuStripSettings_Click(object sender, EventArgs e)
        {
            this.WindowState = WindowState.Normal;
            this.ShowInTaskbar = true;
            this.Visibility = Visibility.Visible;
        }
        private void ContextMenuStripExit_Click(object sender, EventArgs e)
        {
            this.Visibility = Visibility.Hidden;
            this.Close();
        }

        //-- canvas app actions mouse events
        private void canvasAppActions_MouseEnter(object sender, System.Windows.Input.MouseEventArgs e)
        {
            canvasAppActionsBg.BeginAnimation(Canvas.OpacityProperty, FadeIn);
        }
        private void canvasAppActions_MouseLeave(object sender, System.Windows.Input.MouseEventArgs e)
        {
            canvasAppActionsBg.BeginAnimation(Canvas.OpacityProperty, FadeOut);
        }

        //-- move the window from the title label
        private void labelAppName_MouseDown(object sender, MouseButtonEventArgs e)
        {
            if(System.Windows.Input.Mouse.LeftButton == MouseButtonState.Pressed)
                this.DragMove();
        }

        //-- app buttons
        private void buttonAppClose_Click(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        //-- navigation buttons
        private void buttonNavigationStatus_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            canvasStatus.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasUpdate.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasAbout.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            //-- navigation
            canvasNavigation.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasNavigationTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(canvasStatus, FrontPosition);
            Canvas.SetZIndex(canvasUpdate, BackPosition);
            Canvas.SetZIndex(canvasAbout, BackPosition);
            Canvas.SetZIndex(canvasTools, BackPosition);
            //-- navigation
            Canvas.SetZIndex(canvasNavigation, FrontPosition);
            Canvas.SetZIndex(canvasNavigationTools, BackPosition);
        }
        private void buttonNavigationUpdate_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            canvasStatus.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasUpdate.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasAbout.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            //-- navigation
            canvasNavigation.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasNavigationTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(canvasStatus, BackPosition);
            Canvas.SetZIndex(canvasUpdate, FrontPosition);
            Canvas.SetZIndex(canvasAbout, BackPosition);
            Canvas.SetZIndex(canvasTools, BackPosition);
            //-- navigation
            Canvas.SetZIndex(canvasNavigation, FrontPosition);
            Canvas.SetZIndex(canvasNavigationTools, BackPosition);
        }
        private void buttonNavigationAbout_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            canvasStatus.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasUpdate.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasAbout.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            //-- navigation
            canvasNavigation.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasNavigationTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(canvasStatus, BackPosition);
            Canvas.SetZIndex(canvasUpdate, BackPosition);
            Canvas.SetZIndex(canvasAbout, FrontPosition);
            Canvas.SetZIndex(canvasTools, BackPosition);
            //-- navigation
            Canvas.SetZIndex(canvasNavigation, FrontPosition);
            Canvas.SetZIndex(canvasNavigationTools, BackPosition);
        }
        private void buttonNavigationOledTools_Click(object sender, RoutedEventArgs e)
        {            
            //-- update interface
            canvasStatus.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasUpdate.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasAbout.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasTools.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            //-- navigation
            canvasNavigation.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasNavigationTools.BeginAnimation(Canvas.OpacityProperty, FadeIn);

            Canvas.SetZIndex(canvasStatus, BackPosition);
            Canvas.SetZIndex(canvasUpdate, BackPosition);
            Canvas.SetZIndex(canvasAbout, BackPosition);
            Canvas.SetZIndex(canvasTools, FrontPosition);
            //-- navigation
            Canvas.SetZIndex(canvasNavigation, BackPosition);
            Canvas.SetZIndex(canvasNavigationTools, FrontPosition);

            //-- show general/put front
            Canvas.SetZIndex(CanvasTContentGeneral, FrontPosition);
        }

        //-- navigation tools buttons
        private void buttonToolsRestore_Click(object sender, RoutedEventArgs e)
        {
            //-- restore config
            WCF.RestoreDefaultTheme();

            // apply
            Apply();
        }
        private void buttonToolsSave_Click(object sender, RoutedEventArgs e)
        {
            //-- save config
            WCF.ReadInterface();

            if (RCF.PathToTheme != listThemes.SelectedItem.ToString())
            {
                //-- copy config.ini
                WCF.CopyToCurrentTheme();

                //-- copy Script.txt
                ScriptRead.CopyScriptFrom(listThemes.SelectedItem.ToString());               
            }
            else
            {
                WCF.WriteCurrentTools();
            }
            
            //-- reload interface language
            LanguageConfig.LoadLangInterface(WCF.Language2Char);

            //-- apply
            Apply();


            //-- go back to main

            //--- update interface
            canvasStatus.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasUpdate.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasAbout.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            canvasTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            //--- navigation
            canvasNavigation.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            canvasNavigationTools.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(canvasStatus, FrontPosition);
            Canvas.SetZIndex(canvasUpdate, BackPosition);
            Canvas.SetZIndex(canvasAbout, BackPosition);
            Canvas.SetZIndex(canvasTools, BackPosition);
            //--- navigation
            Canvas.SetZIndex(canvasNavigation, FrontPosition);
            Canvas.SetZIndex(canvasNavigationTools, BackPosition);
        }

        //-- about menu
        private void buttonAOmaura_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.omaura.com");
        }
        private void buttonAHelp_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start("http://www.omaura.com/support.php");
        }
        private void buttonAHelpHTML_Click(object sender, RoutedEventArgs e)
        {
            if (File.Exists(InstallPath + "/Resources/Help/omaura-oled(" + RCF.Language + ").html"))
                System.Diagnostics.Process.Start(InstallPath + "/Resources/Help/omaura-oled(" + RCF.Language + ").html");
            else
                System.Diagnostics.Process.Start(InstallPath + "/Resources/Help/omaura-oled(en).html");
        }

        //-- tools menu
        private void buttonCGeneral_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            CanvasTContentGeneral.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            CanvasTContentMessages.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentThemes.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentWeather.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentPlugin.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(CanvasTContentGeneral, FrontPosition);
            Canvas.SetZIndex(CanvasTContentMessages, BackPosition);
            Canvas.SetZIndex(CanvasTContentThemes, BackPosition);
            Canvas.SetZIndex(CanvasTContentWeather, BackPosition);
            Canvas.SetZIndex(CanvasTContentPlugin, BackPosition);
        }
        private void buttonCMessages_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            CanvasTContentGeneral.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentMessages.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            CanvasTContentThemes.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentWeather.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentPlugin.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(CanvasTContentGeneral, BackPosition);
            Canvas.SetZIndex(CanvasTContentMessages, FrontPosition);
            Canvas.SetZIndex(CanvasTContentThemes, BackPosition);
            Canvas.SetZIndex(CanvasTContentWeather, BackPosition);
            Canvas.SetZIndex(CanvasTContentPlugin, BackPosition);
        }
        private void buttonCThemes_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            CanvasTContentGeneral.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentMessages.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentThemes.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            CanvasTContentWeather.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentPlugin.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(CanvasTContentGeneral, BackPosition);
            Canvas.SetZIndex(CanvasTContentMessages, BackPosition);
            Canvas.SetZIndex(CanvasTContentThemes, FrontPosition);
            Canvas.SetZIndex(CanvasTContentWeather, BackPosition);
            Canvas.SetZIndex(CanvasTContentPlugin, BackPosition);
        }
        private void buttonCWeather_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            CanvasTContentGeneral.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentMessages.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentThemes.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentWeather.BeginAnimation(Canvas.OpacityProperty, FadeIn);
            CanvasTContentPlugin.BeginAnimation(Canvas.OpacityProperty, FadeOut);

            Canvas.SetZIndex(CanvasTContentGeneral, BackPosition);
            Canvas.SetZIndex(CanvasTContentMessages, BackPosition);
            Canvas.SetZIndex(CanvasTContentThemes, BackPosition);
            Canvas.SetZIndex(CanvasTContentWeather, FrontPosition);
            Canvas.SetZIndex(CanvasTContentPlugin, BackPosition);
        }
        private void buttonCPlugin_Click(object sender, RoutedEventArgs e)
        {
            //-- update interface
            CanvasTContentGeneral.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentMessages.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentThemes.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentWeather.BeginAnimation(Canvas.OpacityProperty, FadeOut);
            CanvasTContentPlugin.BeginAnimation(Canvas.OpacityProperty, FadeIn);

            Canvas.SetZIndex(CanvasTContentGeneral, BackPosition);
            Canvas.SetZIndex(CanvasTContentMessages, BackPosition);
            Canvas.SetZIndex(CanvasTContentThemes, BackPosition);
            Canvas.SetZIndex(CanvasTContentWeather, BackPosition);
            Canvas.SetZIndex(CanvasTContentPlugin, FrontPosition);
        }
        private void listThemes_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            RT.ReadPreviewTheme(listThemes.SelectedItem.ToString(), this);
        }

        //-- beta weather buttons
        //--- WARNING: need to be integrated to the script language 
        //---
        private void ButtonWeather_Click(object sender, RoutedEventArgs e)
        {
            displayClass.eraseScreen();

            //weather.WeatherDisplay(displayClass);
            displayClass.displayWeather();

            timerTimeCurrent.Stop();
            timerWeatherDisplay.Start();
        }
        private void buttonWeatherSearchCity_Click(object sender, RoutedEventArgs e)
        {
            InternetConnexionUp = HTTPTest.ConnectionAvailable(InternetConnexionUrl);

            if (InternetConnexionUp)
            {
                //--- using weather.com sdk
                //--- more information in the sdk

                listBoxTWeatherCity.Items.Clear();

                //-- init parameters
                int iResults = 0;
                bool cityFound = false;

                for (int iString = 0; iString < 20; iString++)
                    WeatherCitySearchResult[iString] = new string[2];

                //-- read the information of the text box
                string cityToSearch = textBoxCityEnter.Text;

                //-- search
                if (cityToSearch != ""
                    && cityToSearch != "city to search"
                    && cityToSearch != "city not found"
                    && cityToSearch != "no item selected"
                    )
                {
                    string urlWeatherDotCom_Search = "http://xoap.weather.com/search/search?where=" + cityToSearch;

                    try
                    {
                        XmlTextReader reader = new XmlTextReader(urlWeatherDotCom_Search);

                        string strURI = "";
                        string strName = "";

                        while (reader.Read())
                        {
                            switch (reader.NodeType)
                            {
                                #region "element"
                                //--
                                case XmlNodeType.Element:
                                    strURI = reader.NamespaceURI;
                                    strName = reader.Name;

                                    if (reader.HasAttributes)
                                    {
                                        if (reader.Name.Equals("loc"))
                                        {
                                            cityFound = true;

                                            for (int i = 0; i < reader.AttributeCount; i++)
                                            {
                                                reader.MoveToAttribute(i);
                                                if (reader.Name.Equals("id"))
                                                {
                                                    WeatherCitySearchResult[iResults][0] = reader.Value;
                                                    WeatherCitySearchResult[iResults][1] = reader.ReadString();

                                                    listBoxTWeatherCity.Items.Add(WeatherCitySearchResult[iResults][1]);

                                                    iResults++;
                                                }
                                            }
                                        }
                                    }
                                    break;
                                //--
                                #endregion "element"

                                default:
                                    break;
                            }
                        }
                        if (!cityFound)
                            textBoxCityEnter.Text = "city not found";
                    }
                    catch (XmlException eXML)
                    {
                        Log.Write("error occured: " + eXML.Message);
                    }
                }
                else
                {
                    textBoxCityEnter.Text = "city to search";
                }
            }
        }
        private void buttonWeatherSaveCity_Click(object sender, RoutedEventArgs e)
        {            
            InternetConnexionUp = HTTPTest.ConnectionAvailable(InternetConnexionUrl);

            if (InternetConnexionUp)
            {
                if (listBoxTWeatherCity.SelectedItem != null)
                {
                    weather.SaveWeather(WeatherCitySearchResult[listBoxTWeatherCity.SelectedIndex][0],
                        WeatherCitySearchResult[listBoxTWeatherCity.SelectedIndex][1]);

                    weather.UpdateWeatherData();

                    listBoxTWeatherCity.Items.Clear();
                }
                else
                {
                    textBoxCityEnter.Text = "no item selected";
                }
            }
        }
        //--- weather.com link
        private void imageAWeatherDotCom_MouseDown(object sender, MouseButtonEventArgs e)
        {
            WeatherDotComLinkClick();
        }
        private void imageWWeatherDotCom_MouseDown(object sender, MouseButtonEventArgs e)
        {
            WeatherDotComLinkClick();
        }
        private void labelWWeatherDotCom_MouseDown(object sender, MouseButtonEventArgs e)
        {
            WeatherDotComLinkClick();
        }
        private void labelAWeatherDotCom_MouseDown(object sender, MouseButtonEventArgs e)
        {
            WeatherDotComLinkClick();
        }
        public void WeatherDotComLinkClick()
        {
            System.Diagnostics.Process.Start("http://www.weather.com/?prod=xoap&par=" + weather.WeatherID);
        }

        //-- beta updates buttons & interfacefunction
        //--- WARNING: need to plan if auto or manually or both
        private void buttonUSearch_Click(object sender, RoutedEventArgs e)
        {
            if (InternetConnexionUp)
            {
                UpdateSoft.ReadVersion();
                Update_UpdateInterface();
            }
        }
        private void buttonUStableDownload_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(UpdateSoft.OledVersion_Stable_url);
        }
        private void buttonUBetaDownload_Click(object sender, RoutedEventArgs e)
        {
            System.Diagnostics.Process.Start(UpdateSoft.OledVersion_Beta_url);
        }
        private void Update_UpdateInterface()
        {
            labelUVersionBetaText.Content = UpdateSoft.OledVersion_Beta;
            labelUVersionStableText.Content = UpdateSoft.OledVersion_Stable;

            //-- beta
            if (UpdateSoft.CompareVer1AndVer2(UpdateSoft.OledVersion_Beta, UpdateSoft.OledInterface.Version))
            {
                buttonUBetaDownload.IsEnabled = true;
                buttonUBetaDownload.BeginAnimation(System.Windows.Controls.Button.OpacityProperty, FadeIn);
            }
            else
            {
                buttonUBetaDownload.IsEnabled = false;
                buttonUBetaDownload.BeginAnimation(System.Windows.Controls.Button.OpacityProperty, FadeOut);
            }

            //-- stable
            if (UpdateSoft.CompareVer1AndVer2(UpdateSoft.OledVersion_Stable, UpdateSoft.OledInterface.Version))
            {
                buttonUStableDownload.IsEnabled = true;
                buttonUStableDownload.BeginAnimation(System.Windows.Controls.Button.OpacityProperty, FadeIn);
            }
            else
            {
                buttonUStableDownload.IsEnabled = false;
                buttonUStableDownload.BeginAnimation(System.Windows.Controls.Button.OpacityProperty, FadeOut);
            }
        }

        //--
        #endregion "Interface"

        //--
        #endregion "Methods"
    }
}
